Python 24-Day Course - Day 4: Dictionaries

Day 4: Dictionaries

Creating and Accessing Dictionaries

A dictionary is a collection of key-value pairs.

student = {
    "name": "Alice",
    "age": 20,
    "grade": "A"
}

print(student["name"])        # Alice
print(student.get("email", "N/A"))  # N/A (default value)

Key Methods

MethodDescriptionExample
keys()List of keysstudent.keys()
values()List of valuesstudent.values()
items()Key-value pairsstudent.items()
get(k, d)Safe accessstudent.get("age", 0)
update(d)Mergestudent.update({"age": 21})
pop(k)Delete by keystudent.pop("grade")

Iterating Over Dictionaries

scores = {"math": 90, "english": 85, "science": 92}

for subject, score in scores.items():
    print(f"{subject}: {score} points")

# math: 90 points
# english: 85 points
# science: 92 points

Nested Dictionaries

school = {
    "class_1": {"teacher": "Mr. Kim", "students": 30},
    "class_2": {"teacher": "Ms. Lee", "students": 28},
}

print(school["class_1"]["teacher"])  # Mr. Kim

Today’s Exercises

  1. Write a program that counts word frequencies (input a sentence -> count occurrences of each word).
  2. Create a function that merges two dictionaries, adding values for matching keys.
  3. Find the student with the highest average score from a student grades dictionary.

Was this article helpful?